import pandas as pd

# 加载数据
data = pd.read_csv('WA_Fn-UseC_-Telco-Customer-Churn.csv')

# 查看前5行
print(data.head())

# 查看数据信息（列名、类型、缺失值）
print(data.info())

# 删除无用列（客户ID不影响流失）
data = data.drop('customerID', axis=1)

# 处理TotalCharges中的空字符串（转换为数值）
data['TotalCharges'] = pd.to_numeric(data['TotalCharges'], errors='coerce')

# 处理缺失值（TotalCharges中有空值？）
data['TotalCharges'] = pd.to_numeric(data['TotalCharges'], errors='coerce')
data = data.dropna()  # 删除缺失值

# 将分类变量转为数字（例如：Yes→1，No→0）
binary_columns = ['Partner', 'Dependents', 'PhoneService', 'PaperlessBilling', 'Churn']
for col in binary_columns:
    data[col] = data[col].map({'Yes': 1, 'No': 0})

# 对分类变量进行独热编码
data = pd.get_dummies(data, drop_first=True)

# 查看处理后的数据
print(data.head())

from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, confusion_matrix

# 划分特征(X)和目标(y)
X = data.drop('Churn', axis=1)
y = data['Churn']

# 分割数据集（80%训练，20%测试）
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 初始化并训练模型
model = LogisticRegression(max_iter=1000)  # 增加迭代次数确保收敛
model.fit(X_train, y_train)

# 预测测试集
y_pred = model.predict(X_test)

# 评估模型
print("准确率:", accuracy_score(y_test, y_pred))
print("混淆矩阵:\n", confusion_matrix(y_test, y_pred))

import matplotlib.pyplot as plt

# 获取特征重要性（逻辑回归系数）
importance = pd.Series(model.coef_[0], index=X.columns)
importance = importance.sort_values()

# 绘制前10重要特征
plt.figure(figsize=(10,6))
importance.tail(10).plot(kind='barh')
plt.title('Top 10 Features Affecting Churn')
plt.xlabel('Coefficient Value')
plt.savefig('feature_importance.png')  # 保存图片
plt.show()

# 在模型评估代码后添加以下内容
import pandas as pd
from sklearn.metrics import accuracy_score, confusion_matrix

# 计算评估指标
accuracy = accuracy_score(y_test, y_pred)
tn, fp, fn, tp = confusion_matrix(y_test, y_pred).ravel()

# 创建DataFrame并保存为Excel
results_df = pd.DataFrame({
    'Metric': ['Accuracy', 'True Negative', 'False Positive', 'False Negative', 'True Positive'],
    'Value': [accuracy, tn, fp, fn, tp]
})
results_df.to_excel('model_results_auto.xlsx', index=False)

print("评估结果已保存为 model_results_auto.xlsx")


# 保存处理后的数据
data.to_csv('cleaned_data.csv', index=False)
print("数据预处理完成！")

# 导出特征重要性
coefficients = pd.DataFrame({
    'Feature': X.columns,
    'Coefficient': model.coef_[0]
})
coefficients.to_csv('features.csv', index=False)